package com.vincent.shiro;

import com.alibaba.fastjson.JSON;
import com.vincent.common.enums.ResultMapKey;
import com.vincent.common.enums.SessionEnum;
import com.vincent.common.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PermissionFilter extends AccessControlFilter {

    private static Logger logger=Logger.getLogger(PermissionFilter.class);

    private String noPermissionUrl;

    public String getNoPermissionUrl() {
        return noPermissionUrl;
    }

    public void setNoPermissionUrl(String noPermissionUrl) {
        this.noPermissionUrl = noPermissionUrl;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        String pers[] = (String[]) mappedValue;
        if (pers == null || pers.length <= 0) {
            return true;
        }
        Subject subject = SecurityUtils.getSubject();
        boolean permittedAll = subject.isPermittedAll(pers);
        if (permittedAll) {
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        boolean isAjax = RequestUtil.isAjax(httpRequest);
        if(isAjax){
            Map<String,Object> map=new HashMap<String, Object>();
            map.put(ResultMapKey.ERROR.getCode(),"你没有操作权限");
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException e) {
                logger.error("Error:",e);
            }finally {

            return false;
            }
        }
        subject.logout();//退出
        String path = httpRequest.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
        httpRequest.getSession().setAttribute(SessionEnum.ERRORMSG.getCode(), "你没有操作权限");
        httpResponse.sendRedirect(basePath+getNoPermissionUrl());
        return false;
    }
}
